import random
import re
import string
import time
import jwt
import redis as redis
from captcha.image import ImageCaptcha
from django.contrib.auth.hashers import check_password,make_password
from django.http import HttpResponse
from rest_framework.views import APIView
from oasystem2 import settings
from rest_framework.response import Response
from user.check_jwt import check_userjwt, check_user
from user.models import User, Rank, Position, Role, Menu, Salary, Department
from user.serializer import RoleSer, SalarySer, MenuSer, PositionSerializer, RankSerializer, DepSer, UserSer


# 校验用户名
class CheckName(APIView):
    def get(self, request, name):
        if not name:
            return Response({"msg": "用户名获取失败", "oode": 400})

        try:
            User.objects.get(name=name)
            return Response({"msg": "用户已存在", "code": 400})
        except Exception as e:
            return Response({"msg": "ok", "code": 200})


# 校验手机号
class CheckMobile(APIView):
    def get(self, request, mobile):
        if not mobile:
            return Response({"msg": "手机号获取失败", "oode": 400})

        try:
            User.objects.get(mobile=mobile)
            return Response({"msg": "用户已存在", "code": 400})
        except Exception as e:
            return Response({"msg": "ok", "code": 200})


# 登录
class Reg_Log(APIView):
    def post(self, request):
        name = request.data.get("name")
        password = request.data.get('password')
        mobile = request.data.get("mobile")

        rule = r"^1[3-9][0-9]+$"

        # 验证手机号
        if not re.findall(rule, mobile):
            return Response({"code": 400, "msg": "手机号格式错误"})

        # 验证信息是否完整
        if not all([name, mobile, password]):
            return Response({"code": 400, "msg": "请补全登录信息"})

        user_info = User.objects.filter(mobile=mobile).first()  # 查询所有用户
        check_pwd = check_password(password, user_info.user_password)  # 密码解密

        # if not check_pwd:
        #     return Response({"msg": "密码错误", "code": 400})
        # if not user_info:
        #     user_info = User.objects.create(user_name=name, user_password=password, mobile=mobile)
        #     payload = {'id': user_info.id, 'name': user_info.name, 'time': int(time.time()) + 4800}
        #     token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
        #     return Response({"code": 200, "msg": "注册并登录成功", "user": {"name": user_info.name}, "token": token})

        # 判断  如果有密码
        if check_pwd:
            payload = {'id': user_info.id, 'name': user_info.user_name,'dep':user_info.department_id.department_name ,'time': int(time.time()) + 43200}
            token = jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')
            return Response({"code": 200, "msg": "登录成功", "user": {"name": user_info.user_name}, "token": token})
        else:
            return Response({"code": 400, "msg": "密码错误 登录失败"})


# 重置密码
class Reset_Pwd(APIView):
    def put(self,request):
        # 前端获取手机号 密码 确认密码
        mobile = request.data.get('mobile')
        new_pwd = request.data.get('new_pwd')
        two_pwd = request.data.get('two_pwd')

        user_info = User.objects.filter(mobile=mobile).first()

        if not user_info:
            return Response({
                'code':400,
                'msg':'用户不存在'
            })

        if new_pwd != two_pwd:
            return Response({
                'code':400,
                'msg':'密码不正确 请重新输入'
            })

        check_pwd = make_password(new_pwd)  # 加密

        User.objects.update(user_password = check_pwd)

        return Response({
            'code':200,
            'msg':'密码修改成功'
        })


# 图片验证码
class Img_Verify(APIView):
    def get(self, request, img_id):
        code = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        img = ImageCaptcha()

        image = img.generate(code)

        # 写入redis 后期校验
        redis_cli = redis.Redis(host='localhost',port=6379)

        redis_cli.setex('img_%s'%img_id,60,code)
        redis_cli.close()

        return HttpResponse(image, content_type="image/png")


# 校验图片验证码
class CheckImage(APIView):
    def get(self,request):
        uuid = request.query_params.get('imageCodeID')
        code = request.query_params.get('imageCode')

        redis_cli = redis.Redis(host='localhost',port=6379)

        image_code = redis_cli.get('img_%s'%uuid)
        if image_code:
            if image_code.decode().lower() != code.lower():
                return Response({'msg':'验证码输入错误'})
            else:
                return Response({'code':200})
        else:
            return Response({'msg':'验证码错误'})


# 用户 增删改查
class UserApiView(APIView):
    def post(self, request):
        user_name = request.data.get("user_name")
        user_account = request.data.get("user_account")
        user_password = request.data.get("user_password")
        mobile = request.data.get("mobile")
        role_id_id = request.data.get("role_id_id")
        position_id_id = request.data.get("position_id_id")
        rank_id_id = request.data.get("rank_id_id")
        department_id_id = request.data.get("department_id_id")

        if not ([user_name, user_account, mobile, role_id_id, position_id_id, rank_id_id, department_id_id]):
            return Response({"code": 400, "msg": "添加用户信息不完整"})

        make_pwd = make_password(user_password)  # 密码加密
        user = User.objects.create(user_name=user_name, user_account=user_account, mobile=mobile,user_password=make_pwd,
                                   role_id_id=role_id_id, position_id_id=position_id_id, rank_id_id=rank_id_id,
                                   department_id_id=department_id_id)

        user.save()
        return Response({"code": 200, "msg": "添加用户成功"})

    @check_user
    def get(self, request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            user = User.objects.all()
            user_list = []
            for i in user:
                a = {
                    "user_name": i.user_name,
                    "user_account": i.user_account,
                    "user_password": i.user_password,
                    "mobile": i.mobile,
                    "role_id_id": i.role_id.role_name,
                    "position_id_id": i.position_id.position_name,
                    "rank_id_id": i.rank_id.rank_name,
                    "department_id_id": i.department_id.department_name
                }
                user_list.append(a)

            return Response({"code": 200, "msg": "获取成功", 'data': user_list})

        else:
            user_id = payload['id']
            user = User.objects.filter(id=user_id).first()
            ser = UserSer(user)
            return Response({"code": 200, "msg": "没有权限,仅可查询自己", "data": ser.data})

    @check_user
    def put(self, request, payload):
        user_id = payload['id']
        user_info = User.objects.filter(id=user_id).first()

        if not user_info:
            return Response({
                'code': 400, 'msg': '用户不存在'
            })

        ser = UserSer(instance=user_info, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()

        return Response({
            'code': 200, 'msg': '更新成功'
        })

    @check_user
    def delete(self, request, payload):
        user_id = payload['id']
        User.objects.filter(id=user_id).delete()
        return Response({'code': 200, 'msg': '删除成功'})


# 部门 增删改查
class DepartmentAPIView(APIView):
    @check_user
    # 获取所有部门数据
    def get(self, request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            depart = Department.objects.all()
            list = []
            for dep in depart:
                a = {
                    'name':dep.department_name,
                    'parent':dep.parent,
                    'remark':dep.remark
                }
                list.append(a)
            return Response({'code':200,'msg':list})
        else:
            return Response({'code':400,'msg':'没有权限'})

    # 添加一个
    @check_user
    def post(self, request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()

        name = request.data.get("department_name")
        parent = request.data.get('parent')
        remark = request.data.get('remark')

        dep = Department.objects.filter(department_name=name)
        if dep:
            return Response({'msg': '部门存在', 'code': 400})

        if user.role_id_id == 1:
            deps = Department.objects.create(department_name=name,parent=parent,remark=remark)
            deps.save()
            return Response({"code": 200, "msg": "添加部门成功"})
        else:
            return Response({'code':400,'msg':'没有权限'})


# 职级 增删改查
class RankInfoView(APIView):
    # 获取全部职级
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            rank = Rank.objects.all()
            ser = RankSerializer(rank,many=True)
            return Response({'code':200,'msg':ser.data})
        else:
            return Response({'code':400,'msg':'没有权限'})

    # 添加职级
    @check_user
    def post(self,request,payload):
        rank_name = request.data.get('rank_name')
        remark = request.data.get('remark')

        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            rank = Rank.objects.create(rank_name=rank_name,remark=remark)
            rank.save()
            return Response({'code':200,'msg':'添加成功'})

        else:
            return Response({'code':400,'msg':'没有添加权限'})

    # 删除职级
    @check_user
    def delete(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            Rank.objects.filter(id=user_id).delete()
            return Response({"code": 200, "msg": "删除成功"})
        else:
            return Response({'code':400,'msg':'没有权限'})

    # 修改职级
    def put(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            rank = Rank.objects.filter(id=user_id).first()
            ser = RankSerializer(instance=rank, data=request.data)
            ser.is_valid(raise_exception=True)
            ser.save()
            return Response({'code': 200, 'msg': '更新成功'})
        else:
            return Response({'code':400,'msg':'没有权限'})

# 岗位 增删改查
class PositionInfoView(APIView):
    # 获取全部岗位
    @check_user
    def get(self, request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            position = Position.objects.all()
            ser = PositionSerializer(position,many=True)
            return Response({'code': 200, 'msg': ser.data})
        else:
            return Response({'code':400,'msg':'没有查询权限'})

    # 添加岗位
    @check_user
    def post(self, request,payload):
        position_name = request.data.get('position_name')
        remark = request.data.get('remark')

        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            position = Position.objects.create(position_name=position_name, remark=remark)
            position.save()
            return Response({'code': 200, 'msg': '添加成功'})
        else:
            return Response({'code':400,'msg':'没有权限'})

    # 删除岗位
    @check_user
    def delete(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            Position.objects.filter(id=user_id).delete()
            return Response({"code": 200, "msg": "删除成功"})
        else:
            return Response({'code':400,'msg':'没有权限'})

    # 修改岗位
    @check_user
    def put(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            position = Position.objects.filter(id=user_id).first()
            ser = PositionSerializer(instance=position, data=request.data)
            ser.is_valid(raise_exception=True)
            ser.save()
            return Response({'code': 200, 'msg': '更新成功'})
        else:
            return Response({'code':400,'msg':'没有权限'})


# 角色 增删改查
class RoleView(APIView):
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            role = Role.objects.all()
            ser = RoleSer(role,many=True)
            return Response({'code': 200, 'msg': ser.data})
        else:
            return Response({'code':400,'msg':'没有权限'})

    @check_user
    def post(self, request,payload):
        role_name = request.data.get('role_name')
        remark = request.data.get('remark')
        menu_me_urls = request.data.get("menu_me_urls")

        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()

        if user.role_id_id == 1:
            role = Role.objects.create(role_name=role_name, remark=remark,menu_me_urls=menu_me_urls)
            role.save()
            return Response({'code': 200, 'msg': '添加成功'})
        else:
            return Response({'code':400,'msg':'没有权限'})

    @check_user
    def delete(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            Role.objects.filter(id=user_id).delete()
            return Response({"code": 200, "msg": "删除成功"})
        else:
            return Response({'code':400,'msg':'没有权限'})

    @check_user
    def put(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            role = Role.objects.filter(id=user_id).first()
            ser = RoleSer(instance=role, data=request.data)
            ser.is_valid(raise_exception=True)
            ser.save()
            return Response({'code': 200, 'msg': '更新成功'})
        else:
            return Response({'code':400,'msg':'没有权限'})


# 菜单 增删改查
class MenuView(APIView):
    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            menu = Menu.objects.all()
            ser = MenuSer(menu,many=True)
            return Response({'code': 200, 'msg': ser.data})
        else:
            return Response({'code': 400, 'msg': '没有查询权限'})

    @check_user
    def post(self,request,payload):

        menu_name = request.data.get("menu_name")
        menu_url = request.data.get("menu_url")
        menu_icon = request.data.get("menu_icon")
        menu_me_id = request.data.get("menu_me_id")
        remark = request.data.get("remark")
        sort = request.data.get("sort")

        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            menu = Menu.objects.create(menu_name=menu_name, menu_url=menu_url,menu_icon=menu_icon,menu_me_id=menu_me_id,remark=remark,sort=sort)
            menu.save()
            return Response({'code': 200, 'msg': '添加成功'})
        else:
            return Response({'code': 400, 'msg': '没有查询权限'})

    @check_user
    def delete(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            Menu.objects.filter(id=user_id).delete()
            return Response({"code": 200, "msg": "删除成功"})
        else:
            return Response({'code':400,'msg':'没有权限'})

    @check_user
    def put(self, request, payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            menu = Menu.objects.filter(id=user_id).first()
            ser = MenuSer(instance=menu, data=request.data)
            ser.is_valid(raise_exception=True)
            ser.save()
            return Response({'code': 200, 'msg': '更新成功'})
        else:
            return Response({'code':400,'msg':'没有权限'})


# 工资表
class SalaryView(APIView):
    @check_user
    def post(self,request,payload):
        user_id = payload['id']
        name = request.data.get("name")
        user_id_id = request.data.get("user_id_id")
        attendance = request.data.get("attendance")
        industrial_mining = request.data.get("industrial_mining")
        ask_leave = request.data.get("ask_leave")
        basic_wage = request.data.get("basic_wage")
        wage_jobs = request.data.get("wage_jobs")

        sala = Salary.objects.create(name=name,user_id_id=user_id_id,attendance=attendance,
            industrial_mining=industrial_mining,ask_leave=ask_leave,basic_wage=basic_wage,wage_jobs=wage_jobs)
        sala.save()

        return Response({"code":200,"msg":"添加成功"})

    @check_user
    def get(self,request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            sala = Salary.objects.all()
            ser = SalarySer(sala,many=True)
            return Response({'code': 200, 'msg': ser.data})
        else:
            salay = Salary.objects.filter(id=user_id).first()
            ser = SalarySer(salay)
            return Response({'code':200,'msg':ser.data})

    @check_user
    def put(self,request,payload):
        user_id = payload['id']

        salary = Salary.objects.filter(id=user_id).first()
        ser = SalarySer(instance=salary, data=request.data)
        ser.is_valid(raise_exception=True)
        ser.save()

        return Response({'code': 200, 'msg': '更新成功'})

    @check_user
    def delete(self,request,payload):
        user_id = payload['id']
        user = User.objects.filter(id=user_id).first()
        if user.role_id_id == 1:
            Salary.objects.filter(id=user_id).delete()
            return Response({"code":200,"msg":"删除成功"})
        else:
            return Response({'code':400,'msg':'没有权限'})



